Page({
  data: {
    // 用户基础信息
    userId: null,
    username: '',
    gender: '保密',
    currentGenderIndex: 2, // 0:男, 1:女, 2:保密
    birthday: '完善生日信息',
    address: '',
    avatarUrl: '',
    // 新增密码字段，这里假设已知用户密码为123456
    userPassword: '123456' ,

    // 弹窗控制
    showGenderPopup: false,
    showBirthdayPopup: false,

    // 性别选项（字符串数组）
    genderOptions: ['男', '女', '保密'],

    // 日期选择器配置
    currentDate: new Date().getTime(),
    minDate: new Date(1900, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') return `${value}年`;
      if (type === 'month') return `${value}月`;
      if (type === 'day') return `${value}日`;
      return value;
    }
  },

  onLoad() {
    // 从缓存获取登录态
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');

    if (token && userInfo) {
      const genderMap = { '男': 0, '女': 1, '保密': 2 };
      const currentGender = this.convertSexToGender(userInfo.sex);
      
      this.setData({
        userId: userInfo.id,
        username: userInfo.name || '',
        avatarUrl: userInfo.avatar || 'https://via.placeholder.com/100',
        gender: currentGender,
        currentGenderIndex: genderMap[currentGender] || 2,
        birthday: userInfo.birthday || '完善生日信息'
      });
    } else {
      wx.showToast({ title: '请先登录', icon: 'none' });
      wx.navigateTo({ url: '/pages/login/login' });
    }
  },

  convertSexToGender(sex) {
    const genderMap = { 1: '男', 2: '女', 3: '保密' };
    return genderMap[sex] || '保密';
  },

  convertGenderToSex(gender) {
    const sexMap = { '男': 1, '女': 2, '保密': 3 };
    return sexMap[gender] || 3;
  },

  onBack() {
    wx.navigateBack();
  },

  onChangeAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.uploadAvatar(res.tempFilePaths[0]);
      }
    });
  },

  uploadAvatar(tempFilePath) {
    const token = wx.getStorageSync('token');
    const userId = this.data.userId;

    if (!token || !userId) {
      wx.showToast({ title: '登录态失效', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '上传中...' });
    wx.uploadFile({
      url: 'http://localhost/dev-api/upload/avatar',
      filePath: tempFilePath,
      name: 'file',
      header: {
        'Authorization': 'Bearer ' + token
      },
      formData: { userId: userId },
      success: (uploadRes) => {
        wx.hideLoading();
        try {
          const data = JSON.parse(uploadRes.data);
          if (data.code === 200 && data.data?.url) {
            this.setData({ avatarUrl: data.data.url });
            wx.showToast({ title: '头像更新成功' });
          } else {
            wx.showToast({ title: '上传失败', icon: 'none' });
          }
        } catch (e) {
          wx.showToast({ title: '上传数据异常', icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ title: '上传失败', icon: 'none' });
      }
    });
  },

  onUsernameChange(e) {
    this.setData({ username: e.detail || '' });
  },

  onEditGender() {
    this.setData({ showGenderPopup: true });
  },

  onGenderSelect(e) {
    let selectedIndex;
    if (typeof e.detail === 'object' && e.detail.index !== undefined) {
      selectedIndex = e.detail.index;
    } else {
      selectedIndex = e.detail;
    }

    if (selectedIndex < 0 || selectedIndex >= this.data.genderOptions.length) {
      console.error('无效的性别索引:', selectedIndex);
      this.setData({ showGenderPopup: false });
      return;
    }

    const selectedGender = this.data.genderOptions[selectedIndex];
    this.setData({
      gender: selectedGender,
      currentGenderIndex: selectedIndex,
      showGenderPopup: false
    });
  },

  onGenderClose() {
    this.setData({ showGenderPopup: false });
  },

  onEditBirthday() {
    this.setData({ showBirthdayPopup: true });
  },

  onBirthdayConfirm(e) {
    const date = new Date(e.detail);
    const formattedBirthday = `${date.getFullYear()}-${
      (date.getMonth() + 1).toString().padStart(2, '0')
    }-${
      date.getDate().toString().padStart(2, '0')
    }`;
    this.setData({
      birthday: formattedBirthday,
      showBirthdayPopup: false
    });
  },

  onBirthdayCancel() {
    this.setData({ showBirthdayPopup: false });
  },

  onSubmit() {
    const { username, gender, birthday, userId, avatarUrl, userPassword } = this.data;
    const token = wx.getStorageSync('token');

    if (!token || !userId) {
      wx.showToast({ title: '用户信息异常，请重新登录', icon: 'none' });
      wx.navigateTo({ url: '/pages/login/login' });
      return;
    }

    const trimmedUsername = (username || '').trim();
    if (!trimmedUsername) {
      wx.showToast({ title: '请输入用户名', icon: 'none' });
      return;
    }

    const submitData = {
      id: userId,
      nickname: trimmedUsername,
      sex: this.convertGenderToSex(gender),
      birthday: birthday === '完善生日信息' ? null : birthday,
      avatarUrl: avatarUrl || 'https://via.placeholder.com/100',
      // 传递正确的密码值
      rawPassword: userPassword 
    };

    wx.showLoading({ title: '提交中...' });
    wx.request({
      url: 'http://localhost/dev-api/userr/users',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/json'
      },
      data: submitData,
      success: (res) => {
        wx.hideLoading();
        if (res.data?.code === 200) {
          wx.showToast({ title: '修改成功', icon: 'success' });
          setTimeout(() => wx.navigateBack(), 2000);
        } else {
          wx.showToast({ title: res.data?.msg || '修改失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  }
});